BTC_check_HC_id =
{
	{
		if (name _x == BTC_HC_name) then {BTC_HC_id = owner _x;_id = BTC_HC_id;};
	} foreach playableunits;
};
BTC_check_owner_HC =
{
	/*_group = _this;
	if (!isPlayer leader _group) then
	{
		{
			if (owner _x != BTC_HC_id) then {_x setOwner BTC_HC_id;};
		} foreach units _group;
	};*/
};
BTC_HC_PVEH =//BTC_to_HC  
{
	_array = _this select 1;
	_type  = _array select 0;
	switch (true) do
	{
		case (_type == 0) : //city
		{
			private ["_city"];
			_city = _array select 1;
			[_city] spawn BTC_init_main_city;
		};
		case (_type == 1) : //Patrol
		{
			private ["_random","_city_array"];
			_random = _array select 1;
			_spawn_select = _array select 2;
			_city_array = _array select 3;
			[_random,_spawn_select,_city_array] spawn BTC_spawn_patrols;
		};
		case (_type == 2) : //Side mission
		{
			private ["_random","_city_array"];
			_pos = _array select 1;
			[_pos] spawn BTC_sm_spawn_units;
		};		
		/*case (_type == 0) : //Fant
		{
			private ["_city_pos"];
			_city_pos = _array select 1;
			[BTC_enemy_side,[_city_pos],80,3] call BTC_spawn_inf_group;
		};
		case (_type == 1) : //Veh
		{
			private ["_loc_2"];
			_loc_2 = _array select 1;
			[BTC_enemy_side,[_loc_2],"",200,2] call BTC_spawn_veh_group;
		};
		case (_type == 2) : //
		{
			private ["_loc_2"];
			_loc_2 = _array select 1;
			[BTC_enemy_side,[_loc_2],"",200,2] call BTC_spawn_inf_group;
		};*/
	};
};
BTC_city_loop =
{
	sleep 30;//30
	BTC_server_time = 30;
	BTC_outro_condition = false;
	if (BTC_p_HC == 1) then 
	{
		waitUntil {BTC_HC_name != ""};
		waitUntil {(({name _x == BTC_HC_name} count playableUnits) > 0)};	
		[] call BTC_check_HC_id;
	};
	_HC_check = 0;
	_sleep_recap_cap = (BTC_recapping_time / 2) + (random (BTC_recapping_time / 2));
	_sleep_recap = 0;
	while {!BTC_outro_condition} do
	{
		{
			private ["_city","_array_p","_radius"];
			_array_p = [];
			_city = _x;
			_radius = 800;
			if (!isNil {_city getVariable "BTC_act_radius"}) then {_radius = _city getVariable "BTC_act_radius";};
			{
				if (Alive _x && (getpos _x) distance _city < 800 && !((vehicle _x) isKindOf "Air")) then {_array_p = _array_p + [_x]};
			} foreach playableunits;//playableunits
			if (count _array_p > 0 && _city getVariable "BTC_city_act" == 0) then 
			{
				if (BTC_HC_name == "") then {[_city] spawn BTC_init_main_city;} else {BTC_to_HC = [0,_city];BTC_HC_id publicVariableClient "BTC_to_HC";sleep 3;[_city] spawn BTC_init_main_city;};
			};
		} foreach BTC_main_city_array;
		{if ({Alive _x} count units _x == 0) then {deleteGroup _x};} foreach allGroups;
		if (BTC_HC_name != "") then {if (_HC_check > 30) then {_HC_check = 0;[] call BTC_check_HC_id;{_x call BTC_check_owner_HC;} foreach allGroups;} else {_HC_check = _HC_check + 5;};};
		sleep 5;
		BTC_server_time = BTC_server_time + 5;//43200
		if (BTC_server_time >= 43200) then {skipTime 12;BTC_server_time = 0;};
		if (count BTC_main_city_array == 0) then {BTC_outro_condition = true;publicVariable "BTC_outro_condition";BTC_m_PVEH = [4];publicVariable "BTC_m_PVEH";};
		if (BTC_debug == 1) then {private ["_text"];_text = str({local _x} count allUnits);hint _text;BTC_m_PVEH = [5,_text];publicVariable "BTC_m_PVEH";};
		//recap
		if (BTC_p_recapping == 1) then
		{
			_sleep_recap = _sleep_recap + 5;
			if (_sleep_recap > _sleep_recap_cap) then
			{
				_sleep_recap = 0;_sleep_recap_cap = (BTC_recapping_time / 2) + (random (BTC_recapping_time / 2));
				[] spawn BTC_recapping_system;
			};
		};
	
	};
};
BTC_init_main_city =
{
	//Set it activated
	//Spawn a loop to check if the players are gone away (15 min?) -> save the troups and wp in a var. (Add a check to check if the var exist(local to server))
	//If no more units then -> completed, remove from array.//_spawn = [east,[BTC_city_4],"",150,1] spawn BTC_spawn_veh_group;
	_city = _this select 0;
	_city_pos = getPos _city;
	_radius = _city getVariable "BTC_radius";
	_city setVariable ["BTC_city_act",1,false];
	_players = playersNumber BTC_player_side;
	_n = 0;
	if ((BTC_HC_name == "" && isServer) || (BTC_HC_name != "" && !isServer)) then 
	{
		[BTC_enemy_side,_city_pos] call BTC_spawn_defender_groups;
		switch (true) do
		{
			case (_players < 5) : {_n = 2;};
			case (_players > 5 && _players < 11) : {_n = 4;};
			case (_players > 11) : {_n = 7;};
		};
		_fant    = ceil (floor (random _n)) + (_n * BTC_enemy_n);
		for "_i" from 0 to (_fant - 1) do
		{
			[BTC_enemy_side,[_city_pos],80,3] call BTC_spawn_inf_group;
		};
		_n = 0;
		switch (true) do
		{
			case (_players < 5) : {_n = 1;};
			case (_players > 5 && _players < 11) : {_n = 2;};
			case (_players > 11) : {_n = 3;};
		};
		_veh_n = round(random (_n * BTC_enemy_n));
		for "_i" from 1 to _veh_n do
		{
			_loc_2 = [(_city_pos select 0) + (random (_radius / 2) - random (_radius / 2)), (_city_pos select 1) + (random (_radius / 2) - random (_radius / 2)), 0];
			[BTC_enemy_side,[_loc_2],"",200,2] call BTC_spawn_veh_group;
		};
		_random = random 1;
		switch (true) do
		{
			case (_random < 0.2)                   : {};
			case (_random >= 0.2 && _random < 0.8) : {[BTC_enemy_side,_city_pos,(_radius / 2)] call BTC_spawn_sniper;};
			case (_random >= 0.8)   : {[BTC_enemy_side,_city_pos,(_radius / 2)] call BTC_spawn_sniper;[BTC_enemy_side,_city_pos,(_radius / 2)] call BTC_spawn_sniper;};
		};
		_houses = [_city_pos,_radius,(round random (5 * BTC_enemy_n))] spawn BTC_spawn_house_patrols;
		if (BTC_p_arty == 1 && _players > 5) then 
		{
			if (random 1 > 0.6) then {_mortar = [_city_pos] spawn BTC_mortar;if (BTC_debug == 1) then {BTC_m_PVEH = [5,"MORTAR SPAWNED"];publicVariable "BTC_m_PVEH";};};
		};
		if (BTC_debug == 1) then {private ["_text"];_text = format ["PLAYERS: %1   FANT: %2   VEH: %3",_players,_fant,_veh_n];hint _text;BTC_m_PVEH = [5,_text];publicVariable "BTC_m_PVEH";};
	};
	sleep 10;
	if (isServer) then
	{
		_cond = true;
		_n = 0;
		while {_cond} do 
		{
			private ["_array_u","_array_p"];
			_array_u = [];_array_p = [];
			{
				if (Alive _x && side _x != BTC_player_side && _x distance _city < (_radius + 200)) then {_array_u = _array_u + [_x]};
			} foreach allUnits;
			if (count _array_u < 4) then {_spawn = [_city] spawn BTC_city_cleared;_cond = false;};
			{
				if (Alive _x && _x distance _city < (_radius + 500)) then {_array_p = _array_p + [_x]};
			} foreach playableunits;
			if (count _array_p == 0) then {_n = _n + 10;} else {_n = 0;};
			if (_n > 600) then {_spawn = [_city,_radius] spawn BTC_city_deactivated;_city setVariable ["BTC_city_act",0,false];_cond = false;};//600
			sleep 10;
		};
	};
};
BTC_city_cleared =
{
	_city = _this select 0;
	_city setVariable ["BTC_city_status",1,true];
	hint "City has been secured";
	BTC_main_city_array = BTC_main_city_array - [_city];
	BTC_city_clear = [0,_city];publicVariable "BTC_city_clear";
};
BTC_city_deactivated =
{
	_city   = _this select 0;
	_radius = _this select 1;
	private ["_array_p"];
	_cond = false;
	while {!_cond} do
	{
		_array_p = [];
		{
			if (Alive _x && _x distance _city < (_radius + 300)) then {_array_p = _array_p + [_x]};
		} foreach playableunits;
		if (count _array_p == 0) then {_cond = true;};
	};
	_array_u = [];
	{
		if (Alive _x && side _x != BTC_player_side && _x distance _city < (_radius + 200)) then {_array_u = _array_u + [_x]};
	} foreach allUnits;
	{deletevehicle _x;} foreach _array_u;
	sleep 1;
	{if (count units _x == 0) then {deleteGroup _x};} foreach allGroups;
};
BTC_recapping_system =
{
	_total_city = count BTC_main_city;
	_captured_city = _total_city - (count BTC_main_city_array);
	_prob = (_captured_city * 100)/ _total_city;
	_cond = false;
	{
		if (!_cond && _x getVariable "BTC_city_status" == 1) then
		{
			if ((random 100 + 20 + random 10) < (_prob/2)) then
			{
				_cond = true;
				_x spawn BTC_city_recapping;
			};
		};
	} foreach BTC_main_city;
};
BTC_city_recapping =
{
	_city = _this;
	[BTC_enemy_side,getpos _city] call BTC_spawn_defender_groups;
	[BTC_enemy_side,getpos _city] call BTC_spawn_defender_groups;
	[BTC_enemy_side,getpos _city] call BTC_spawn_defender_groups;
	[BTC_enemy_side,[getpos _city],"",200,0.2] call BTC_spawn_veh_group;
	if (random 1 > 0.5) then {[BTC_enemy_side,[getpos _city],"",200,0.2] call BTC_spawn_veh_group;};
	BTC_city_under_attack = BTC_city_under_attack + [_city];
	BTC_city_clear = [8,_city];publicVariable "BTC_city_clear";
	_cond = false;
	_players_time = 0;
	_AI_left = 1;
	while {!_cond} do
	{
		_array_p = [];_array_u = [];
		{
			if (Alive _x && _x distance _city < 600) then {_array_p = _array_p + [_x]};
		} foreach playableunits;
		{
			if (side _x != BTC_player_side && Alive _x && _x distance _city < 600) then {_array_u = _array_u + [_x]};
		} foreach allUnits;
		if (count _array_p == 0) then {_players_time = _players_time + 1;};
		if (count _array_u == 0) then {_AI_left = 0;_cond = true;};
		if (_players_time > 900) then {_cond = true;};
		sleep 1;
	};
	if (_AI_left == 0) then 
	{
		BTC_city_clear = [10,_city];publicVariable "BTC_city_clear";
		BTC_city_under_attack = BTC_city_under_attack - [_city];
	} 
	else
	{
		_city setVariable ["BTC_city_status",0,true];
		BTC_city_clear = [9,_city];publicVariable "BTC_city_clear";
		hint "City has been conquered by the enemy!";
		BTC_main_city_array = BTC_main_city_array + [_city];
		_cond = false;
		while {!_cond} do
		{
			_array_p = [];
			{
				if (Alive _x && _x distance _city < (_radius + 300)) then {_array_p = _array_p + [_x]};
			} foreach playableunits;
			if (count _array_p == 0) then {_cond = true;};
		};
		_array_u = [];
		{
			if (Alive _x && side _x != BTC_player_side && _x distance _city < (_radius + 200)) then {_array_u = _array_u + [_x]};
		} foreach allUnits;
		{deletevehicle _x;} foreach _array_u;
		sleep 1;
		{if (count units _x == 0) then {deleteGroup _x};} foreach allGroups;
	};
};
BTC_clean_up =
{
	while {true} do 
	{
		sleep 120;
		{
			private ["_obj"];_obj = _x;
			if (({_x distance _obj < 150} count playableUnits) == 0 && isNil {_dead getVariable "BTC_dont_delete"}) then {deleteVehicle _obj};
		} foreach (allMissionObjects "groundweaponholder");
		{
			private ["_dead"];_dead = _x;
			if (({_x distance _dead < 300} count playableUnits) == 0 && isNil {_dead getVariable "BTC_dont_delete"}) then {deleteVehicle _dead};
		} foreach alldead;
	};
};
BTC_spawn_defender_groups =
{
	//_spawn = [east,[pos_1,pos_2],50,7,1] spawn BTC_spawn_inf_group;
	_side        = _this select 0;
	_zone        = _this select 1;
	switch (typeName _zone) do
	{
		case "ARRAY" :{_zone = _zone;};
		case "STRING":{_zone = getMarkerPos _zone;};
		case "OBJECT":{_zone = position _zone;};
	};
	private ["_group","_pos","_newZone","_unit_type","_wp"];
	_group = createGroup _side;
	_pos = [(_zone select 0) + (random 60 - random 60), (_zone select 1) + (random 60 - random 60), 0];
	_newZone = [_pos, 0, 100, 3, 0, 60 * (pi / 180), 0, []] call BIS_fnc_findSafePos;
	_group createUnit [BTC_type_TL, _newZone, [], 0, "NONE"];
	for "_i" from 0 to (round random (2 * BTC_enemy_n)) do
	{
		_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
		_group createUnit [_unit_type, _newZone, [], 0, "NONE"];
	};
	_group createUnit [BTC_type_medic, _newZone, [], 0, "NONE"];
	//if !(isClass(configFile >> "cfgPatches" >> "asr_ai_main")) then {{_x setSkill ["aimingAccuracy", BTC_AI_skill];} foreach units _group;};
	if (BTC_p_skill == 1) then {[_group] call BTC_AI_init;};
	_wp = _group addWaypoint [_newZone, 0];
	_wp setWaypointType "SENTRY";
	_wp setWaypointCombatMode "RED";
	_wp setWaypointBehaviour "AWARE";
	_wp setWaypointSpeed "FULL";	
};
BTC_spawn_sniper =
{
	_side        = _this select 0;
	_spawn_zone  = _this select 1;
	_radius      = _this select 2;
	_loc_x = _spawn_zone select 0;
	_loc_y = _spawn_zone select 1;
	_loc_2 = [_loc_x + (random _radius - random _radius), _loc_y + (random _radius - random _radius), 0];
	_zone = [_loc_2, 0, 100, 1, 0, 60 * (pi / 180), 0, []] call BIS_fnc_findSafePos;
	_group = createGroup _side;
	_group createUnit [BTC_type_sniper, _zone, [], 0, "NONE"];
	_wp = _group addWaypoint [_zone, 0];
	_wp setWaypointType "SENTRY";
	_wp setWaypointCombatMode "RED";
	_wp setWaypointBehaviour "STEALTH";
	_wp setWaypointSpeed "FULL";
};
BTC_spawn_inf_group =
{
	//_spawn = [east,[pos_1,pos_2],50,1] spawn BTC_spawn_inf_group;
	private ["_pos","_house","_n_units"];
	_side        = _this select 0;
	_spawn_zones = _this select 1;
	_r_patrol    = _this select 2;
	_random      = _this select 3;
	_group = createGroup _side;
	_center = _spawn_zones select 0;
	_houses = [_center,500] call BTC_get_houses;
	if (count _houses == 0) then {_pos = _center;} else {_house  = _houses select (round (random ((count _houses) - 1)));_pos = _house buildingPos 1;};
	if (typeName _pos != "ARRAY") then {_pos = getPos _center;};
	_group createUnit [BTC_type_TL, _pos, [], 0, "NONE"];
	_zone = [(_pos select 0) + (random 120 - random 120), (_pos select 1) + (random 120 - random 120), 0];
	[_group,_pos] spawn
	{
		
		_group = _this select 0;
		_pos = _this select 1;
		_n_units     = floor ((random 2) + (random (2 * BTC_enemy_n)));
		sleep 0.5;
		for "_i" from 0 to (_n_units - 1) do
		{
			_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
			_group createUnit [_unit_type, _pos, [], 0, "NONE"];
			sleep 0.5;
		};
		_group createUnit [BTC_type_medic, _pos, [], 0, "NONE"];
		if (BTC_p_skill == 1) then {[_group] call BTC_AI_init;};
	};
	if (_random > 1) then {_random = random 1;};
	switch (true) do
	{
		case (_random < 0.33) : {_wp = _group addWaypoint [_zone, 0];_wp setWaypointType "SENTRY";_wp setWaypointCombatMode "RED";_wp setWaypointBehaviour "AWARE";_wp setWaypointSpeed "FULL";};
		case (_random > 0.32 && _random < 0.5) : {_wp = _group addWaypoint [_zone, 0];_wp setWaypointType "GUARD";_wp setWaypointCombatMode "RED";_wp setWaypointBehaviour "AWARE";_wp setWaypointSpeed "FULL";};
		case (_random > 0.49) : {[_group, _zone, _r_patrol] spawn BTC_task_patrol;};
	};
};
BTC_spawn_veh_group =
{
	//_spawn = [east,[pos_1,pos_2],"",150,1] spawn BTC_spawn_veh_group;
	_side        = _this select 0;
	_spawn_zones = _this select 1;
	_veh_type    = _this select 2;
	_r_patrol    = _this select 3;
	_random      = _this select 4;
	_zone_array  = _spawn_zones select (round (random ((count _spawn_zones) - 1)));
	_zone = _zone_array;
	switch (typeName _zone_array) do
	{
		case "ARRAY" :{_zone = _zone_array;};
		case "STRING":{_zone = getMarkerPos _zone_array;};
		case "OBJECT":{_zone = position _zone_array;};
	};
	_group = createGroup _side;
	if (_veh_type == "") then {_veh_type = BTC_type_vehicles select (round (random ((count BTC_type_vehicles) - 1)));};
	_newZone = [];
	_newZone = [_zone, 0, _r_patrol, 10, 0, 60 * (pi / 180), 0, []] call BIS_fnc_findSafePos;
	_veh = createVehicle [_veh_type, _newZone, [], 0, "NONE"];
	BTC_type_crewmen createUnit [_zone, _group, "this moveinDriver _veh"];
	_gunner = _veh emptyPositions "gunner";
	_commander = _veh emptyPositions "commander";
	_cargo = (_veh emptyPositions "cargo") - 1;
	if (_gunner > 0) then {BTC_type_crewmen createUnit [_zone, _group, "this moveinGunner _veh;this assignAsGunner _veh;"];};
	if (_commander > 0) then {BTC_type_crewmen createUnit [_zone, _group, "this moveinCommander _veh;this assignAsCommander _veh;"];};
	if (_cargo > 0) then
	{
		for "_i" from 0 to _cargo do
		{
			_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
			_unit_type createUnit [_zone, _group, "this moveinCargo _veh;this assignAsCargo _veh;"];
		};
	};
	//if !(isClass(configFile >> "cfgPatches" >> "asr_ai_main")) then {{_x setSkill ["aimingAccuracy", BTC_AI_skill];} foreach units _group;};
	if (BTC_p_skill == 1) then {[_group] call BTC_AI_init;};
	if (_random > 1) then {_random = random 1;};
	switch (true) do
	{
		case (_random < 0.33) : {_wp = _group addWaypoint [_zone, 0];_wp setWaypointType "SENTRY";_wp setWaypointCombatMode "RED";_wp setWaypointBehaviour "AWARE";_wp setWaypointSpeed "FULL";};
		case (_random > 0.32 && _random < 0.5) : {_wp = _group addWaypoint [_zone, 0];_wp setWaypointType "GUARD";_wp setWaypointCombatMode "RED";_wp setWaypointBehaviour "AWARE";_wp setWaypointSpeed "FULL";};
		case (_random > 0.49) : {[_group, _zone, _r_patrol] spawn BTC_task_patrol;};
	};
};
BTC_spawn_house_patrols =
{
	_loc  = _this select 0;
	_area = _this select 1;
	_n    = _this select 2;
	_houses = [_loc,_area] call BTC_get_houses;
	if (count _houses > 0) then
	{
		for "_i" from 0 to _n do
		{
			private ["_group","_unit_type","_house","_patrol","_id"];
			if (count _houses > 0) then
			{
				_group = createGroup BTC_enemy_side;
				_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
				_group createUnit [_unit_type, [0,0,0], [], 0, "NONE"];	
				_id = (round (random ((count _houses) - 1)));
				_house = _houses select _id;
				_houses set [_id,0];
				_houses = _houses - [0];
				_patrol = [leader _group,_house] spawn BTC_house_patrol;
			};
		};
		if (BTC_debug == 1) then {hint format ["fnc_spawn_house_patrols - %1",_n];};
	};
};
BTC_get_houses = 
{
	_pos       = _this select 0;
	_radius    = _this select 1;
	_buildings = nearestObjects [_pos, ["Building"], _radius];
	_useful    = [];
	{ 
		if (format["%1", _x buildingPos 2] != "[0,0,0]" && damage _x == 0 && !(typeOf _x in BTC_house_not_available)) then
		{ 
			_useful set [count _useful, _x]; 
		}; 
	} forEach _buildings; 
	_useful	
};
BTC_house_patrol =
{
	_unit  = _this select 0;
	_house = _this select 1;
	_n_pos = 0;
	_timeout = time;
	while {format ["%1", _house buildingPos _n_pos] != "[0,0,0]" } do {_n_pos = _n_pos + 1};
	_max_pos = _n_pos;
	_n_pos   = round (random _max_pos);
	group _unit setBehaviour "AWARE";
	group _unit setCombatMode "RED";
	_patrol = (round (random 1));
	_unit setPos (_house buildingPos 0);
	if (_patrol == 1) then
	{
		for "_i" from 0 to (round (random 1)) do
		{		
			private ["_unit_type"];
			_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
			(group _unit) createUnit [_unit_type, [0,0,8000], [], 0, "NONE"];
		};
		{_x setPos (_house buildingPos 0);} foreach units (group _unit);
		{deleteWaypoint _x;} foreach waypoints (group _unit);
		while {Alive _unit && canStand _unit && canMove _unit} do 
		{
			{_x doMove (_house buildingpos _n_pos);} foreach units (group _unit);
			group _unit setSpeedMode "LIMITED";
			_n_pos = _n_pos + 1;
			if (_n_pos == _max_pos) then {_n_pos = 0;};
			_timeout = time + 50;
			waitUntil {sleep 1; (unitReady _unit || moveToCompleted _unit || moveToFailed _unit || !alive _unit || _timeout < time)};
			doStop _unit;
			sleep 10;
		};	
	}
	else
	{
		_unit setPos (_house buildingPos _n_pos);
		{deleteWaypoint _x;} foreach waypoints (group _unit);
		doStop _unit;
	};
};
BTC_task_patrol =
{
	//From BIS module
	private ["_grp", "_pos", "_maxDist"];
	_grp = _this select 0;
	_pos = _this select 1;
	_maxDist = _this select 2;
	_pos = getpos (leader _grp);
	hint format ["%1",_this];
	_grp setBehaviour "SAFE";
	{_x setBehaviour "SAFE";} foreach units _grp;

	private ["_prevPos"];
	_prevPos = _pos;
	for "_i" from 0 to (2 + (floor (random 3))) do
	{
		private ["_wp", "_newPos"];
		_newPos = [_prevPos, 50, _maxDist, 1, 0, 60 * (pi / 180), 0, []] call BIS_fnc_findSafePos;

		_prevPos = _newPos;

		_wp = _grp addWaypoint [_newPos, 0];
		_wp setWaypointType "MOVE";
		_wp setWaypointCompletionRadius 20;
		_wp setWaypointCombatMode "RED";

		if (_i == 0) then
		{
			_wp setWaypointSpeed "LIMITED";
			_wp setWaypointFormation "STAG COLUMN";
			_wp setWaypointCombatMode "RED";
			_wp setWaypointBehaviour "SAFE";
		};
	};

	private ["_wp"];
	_wp = _grp addWaypoint [_pos, 0];
	_wp setWaypointType "CYCLE";
	_wp setWaypointCompletionRadius 20;

	true	
};
BTC_mortar =
{
	private ["_random","_pos","_group","_newZone","_mortar"];
	_pos = _this select 0;
	_group = createGroup BTC_enemy_side;
	_newZone = [_pos, 1, 200, 1, 0, 60 * (pi / 180), 0] call BIS_fnc_findSafePos;
	_mortar = createVehicle [BTC_type_mortar, _newZone, [], 0, "NONE"];
	_round_1 = createVehicle ["Land_BagFence_Round_F", [_newZone select 0,(_newZone select 1) + 1.5,0], [], 0, "NONE"];
	_round_2 = createVehicle ["Land_BagFence_Round_F", [_newZone select 0,(_newZone select 1) - 1.5,0], [], 0, "NONE"];
	_round_1 setDir 180;_round_1 setpos [_newZone select 0,(_newZone select 1) + 1.5,0];_round_2 setpos [_newZone select 0,(_newZone select 1) - 1.5,0];
	BTC_type_crewmen createUnit [_newZone, _group, "this moveinGunner _mortar"];
	_group createUnit [BTC_type_crewmen, _newZone, [], 0, "NONE"];
	_mortar_control = [_mortar] spawn BTC_mortar_control;
};
BTC_mortar_control =
{
	private ["_mortar","_fired","_targets_list","_mortar"];
	if (BTC_debug == 1) then {hint "fnc_mortar_control"};
	_mortar = _this select 0;
	{_x addEventHandler ["Killed", {(_this select 0) setpos getpos vehicle (_this select 0)}];} foreach crew _mortar;
	_fired  = false;
	//sleep 120;
	while {count crew _mortar > 0 && Alive _mortar} do
	{
		{
			if (side _x == BTC_enemy_side && !_fired) then
			{
				_targets_list = leader _x nearTargets 2500;
				if ({_x select 2 == BTC_player_side} count _targets_list > 0) then
				{
					{if (_x select 2 == BTC_player_side && !_fired && (count ((_x select 0) nearEntities [BTC_enemy_men, 100]) == 0) && (_x select 0) distance _mortar < 3500) then {if (BTC_debug == 1) then {hint format ["Get target %1 - %2",_mortar, mapGridPosition (_x select 0)];};[_mortar,_x select 0] spawn BTC_fire_mortar;_fired = true;}} foreach _targets_list;
				};
			};
		} foreach allGroups;
		if (_fired) then {sleep BTC_arty_reload + random 60;};
		_fired = false;
	};
};
BTC_fire_mortar =
{
	_mortar = _this select 0;
	_pos    = _this select 1;
	_EH     = _mortar addEventHandler ["fired", {deletevehicle (nearestobject[_this select 0, _this select 4])}];
	(gunner _mortar) lookAt _pos;
	for "_i" from 0 to (BTC_arty_salvo - 1) do
	{
		_mortar setVehicleAmmo 1;
		_mortar fire (weapons _mortar select 0);
		sleep 2;
	};
	sleep (10 + random 5); 
	for "_i" from 0 to (BTC_arty_salvo - 1) do
	{	
		_bullet = "Sh_82mm_AMOS" createVehicle [(_pos select 0)+ (random BTC_arty_dispersion - random BTC_arty_dispersion), (_pos select 1)+ random (random BTC_arty_dispersion - random BTC_arty_dispersion), (_pos select 2)+ 100];  
		_bullet setvelocity [0,0,- 50];
		sleep 2;
	};
	_mortar setVehicleAmmo 1;
	_mortar removeAllEventHandlers "fired";
};
BTC_patrols_control = 
{
	BTC_AI_id_n = 0;
	sleep 15;
	while {true} do
	{
		if (count BTC_main_city_array > 2) then
		{
			_n_p = count playableunits;//SwitchableUnits playableUnits
			_spawn_ratio = 0;
			if (_n_p < 8) then {_spawn_ratio = (1 * BTC_p_n_patrol) + (random floor 3);};
			if (_n_p >= 8) then {_spawn_ratio = (1 * BTC_p_n_patrol) + (random floor 3);};
			//check patrols
			_patrols = 0;
			{if (count units _x != 0 && !isNil {_x getVariable "BTC_patrols_ID"}) then {_patrols = _patrols + 1;};} foreach allGroups;
			if ((_patrols - _spawn_ratio) < 3) then 
			{
				private ["_n"];
				_n = abs (_patrols - _spawn_ratio);
				if (BTC_debug == 1) then {player sideChat format ["Spawning patrol = %1",_n];};
				for "_i" from 0 to _n do
				{
					private ["_spawn_select","_array"];
					_spawn_select = objNull;
					_array = BTC_main_city_array;
					_cond = true;
					while {_cond} do
					{
						private ["_n"];
						if (count _array == 0) then {_cond = false;};
						_n = round (random ((count _array) - 1));
						if ((_array select _n) getVariable "BTC_city_act" != 0) then {_array set [_n,0];_array = _array - [0];} else {_spawn_select = _array select _n;_cond = false;};
						sleep 0.1;
					};
					if (!isNull _spawn_select) then {if (BTC_HC_name == "") then {[0,_spawn_select,_array] spawn BTC_spawn_patrols;} else {BTC_to_HC = [1,0,_spawn_select,_array];BTC_HC_id publicVariableClient "BTC_to_HC";};};
					sleep 2;
				};
			};
		};
		//sleep
		sleep 300;//300
	};
};
BTC_spawn_patrols =
{
	_random = _this select 0;//0 random, 1 inf, 2 moto, 3 heli
	_spawn_select = _this select 1;
	_city_array = _this select 2;
	if (isNil "BTC_AI_id_n") then {BTC_AI_id_n = 0;};
	if (_random == 0) then
	{
		private ["_n"];
		_n = random 100;
		switch (true) do
		{
			case (_n < 40)            : {_random = 1;};
			case (_n > 40 && _n < 90) : {_random = 2;};
			case (_n > 90 && _n < 96) : {_random = 3;};
			case (_n > 96)            : {_random = 4;};
		};
	};
	switch (true) do
	{
		case (_random == 1) : 
		{
			private ["_random_start_pos"];
			_random_start_pos = getpos _spawn_select;
			_n_units     = 4 + (random (5 * BTC_enemy_n));
			if (BTC_debug == 1) then {player sideChat format ["Spawning patrol INF = %1",_n_units];};
			_group = createGroup BTC_enemy_side;
			if (!isServer) then {_group setVariable ["BTC_patrols_ID",BTC_AI_id_n,true];} else {_group setVariable ["BTC_patrols_ID",BTC_AI_id_n,false];};BTC_AI_id_n = BTC_AI_id_n + 1;
			if (format ["%1",_random_start_pos] == "[0,0,0]" || _random_start_pos distance [0,0,0] < 150) then {_random_start_pos = getpos (_city_array select 0);};
			_group createUnit [BTC_type_TL, _random_start_pos, [], 0, "NONE"];
			for "_i" from 0 to (_n_units - 1) do
			{
				_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
				_group createUnit [_unit_type, _random_start_pos, [], 0, "NONE"];
				sleep 0.1;
			};
			_group createUnit [BTC_type_medic, _random_start_pos, [], 0, "NONE"];
			if (BTC_p_skill == 1) then {[_group] call BTC_AI_init;};
			_spawn = [_group,_city_array] spawn BTC_add_waypoint_patrols;		
		};
		case (_random == 2) : 
		{
			private ["_newZone","_random_start_pos"];
			if (BTC_debug == 1) then {player sideChat format ["Spawning patrol VEH = %1",true];};
			_group = createGroup BTC_enemy_side;
			if (!isServer) then {_group setVariable ["BTC_patrols_ID",BTC_AI_id_n,true];} else {_group setVariable ["BTC_patrols_ID",BTC_AI_id_n,false];};BTC_AI_id_n = BTC_AI_id_n + 1;
			_veh_type = BTC_type_motorized select (round (random ((count BTC_type_motorized) - 1)));
			_random_start_pos = getpos _spawn_select;
			_newZone = [];
			if (count (_random_start_pos nearRoads 150) > 0) then {_newZone = getPos ((_random_start_pos nearRoads 150) select 0)} else {_newZone = _random_start_pos findEmptyPosition [1, 200, _veh_type];};
			_veh = createVehicle [_veh_type, _newZone, [], 0, "NONE"];
			[_veh,_group,false,"",BTC_type_crewmen] call BIS_fnc_spawnCrew;
			_group selectLeader (driver _veh);
			_cargo = (_veh emptyPositions "cargo") - 1;
			if (_cargo > 0) then
			{
				for "_i" from 0 to _cargo do
				{
					_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
					_unit_type createUnit [_random_start_pos, _group, "this moveinCargo _veh;this assignAsCargo _veh;"];
				};
			};
			if (BTC_p_skill == 1) then {[_group] call BTC_AI_init;};
			_spawn = [_group,_city_array] spawn BTC_add_waypoint_patrols;		
		};
		case (_random == 3) : 
		{
			private ["_random_start_pos"];
			if (BTC_debug == 1) then {player sideChat format ["Spawning patrol HELO = %1",true];};
			_random_start_pos = getpos _spawn_select;
			_group = createGroup BTC_enemy_side;
			if (!isServer) then {_group setVariable ["BTC_patrols_ID",BTC_AI_id_n,true];} else {_group setVariable ["BTC_patrols_ID",BTC_AI_id_n,false];};BTC_AI_id_n = BTC_AI_id_n + 1;
			_heli_type = BTC_type_heli_transport select (round (random (((count BTC_type_heli_transport) - 1))));
			_veh = createVehicle [_heli_type, _random_start_pos, [], 0, "FLY"];
			[_veh,_group,false,"",BTC_type_pilot] call BIS_fnc_spawnCrew;
			_group selectLeader (driver _veh);
			_cargo = (_veh emptyPositions "cargo") - 1;
			if (_cargo > 0) then
			{
				for "_i" from 0 to _cargo do
				{
					_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
					_unit_type createUnit [_random_start_pos, _group, "this moveinCargo _veh;this assignAsCargo _veh;"];
				};
			};
			if (BTC_p_skill == 1) then {[_group] call BTC_AI_init;};
			_spawn = [_group,_city_array] spawn BTC_add_waypoint_patrols;
		};
		case (_random == 4) : 
		{
			private ["_random_start_pos"];
			if (BTC_debug == 1) then {player sideChat format ["Spawning patrol HELO ATTACK = %1",true];};
			_random_start_pos = getpos _spawn_select;
			_group = createGroup BTC_enemy_side;
			if (!isServer) then {_group setVariable ["BTC_patrols_ID",BTC_AI_id_n,true];} else {_group setVariable ["BTC_patrols_ID",BTC_AI_id_n,false];};BTC_AI_id_n = BTC_AI_id_n + 1;
			_array = BTC_type_plane + BTC_type_heli;
			_heli_type = _array select (round (random (((count _array) - 1))));
			_veh = createVehicle [_heli_type, _random_start_pos, [], 0, "FLY"];
			[_veh,_group,false,"",BTC_type_pilot] call BIS_fnc_spawnCrew;
			_cargo = (_veh emptyPositions "cargo") - 1;
			if (_cargo > 0) then
			{
				for "_i" from 0 to _cargo do
				{
					_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
					_unit_type createUnit [_random_start_pos, _group, "this moveinCargo _veh;this assignAsCargo _veh;"];
				};
			};
			if (BTC_p_skill == 1) then {[_group] call BTC_AI_init;};
			_spawn = [_group,_city_array] spawn BTC_add_waypoint_patrols;
		};
	};
};
BTC_add_waypoint_patrols =
{
	private ["_wp","_wp_1"];
	_group = _this select 0;
	_array = _this select 1;
	waitUntil {!isNil {_group getVariable "BTC_patrols_ID"}};
	//diag_log text format ["WP Patrol: %1 ARRAY: %2",_group getVariable "BTC_patrols_ID",_array];
	_pos_tl = getPos leader _group;
	_pos_patrol = [];_locs = [];
	{
		if (_x distance _pos_tl < 2500 && _x distance _pos_tl > 500) then {_locs = _locs + [_x];};
	} foreach _array;
	if (count _locs == 0) then {_pos_patrol = getPos (_array select (round (random (((count _array) - 1)))));} else {_pos_patrol = getPos (_locs select (round (random (((count _locs) - 1)))));};
	

	//diag_log text format ["_pos_patrol %1 _array: %2 _locs %3",_pos_patrol,_array,_locs];
	while {(count (waypoints _group)) > 0} do
	{
		deleteWaypoint ((waypoints _group) select 0);
	};
	
	if ((vehicle leader _group) isKindOf "Air" || (vehicle leader _group) isKindOf "LandVehicle") then {(vehicle leader _group) setFuel 1;};
	_group setBehaviour "SAFE";
	_wp = _group addWaypoint [_pos_patrol, 0];
	_wp setWaypointType "MOVE";
	_wp setWaypointCompletionRadius 20;
	_wp setWaypointCombatMode "RED";
	_wp setWaypointSpeed "LIMITED";
	_wp setWaypointFormation "STAG COLUMN";
	
	if !((vehicle leader _group) isKindOf "Air") then
	{
		for "_i" from 0 to (2 + (floor (random 3))) do
		{
			private ["_wp", "_newPos"];
			
			_newPos = [(_pos_patrol select 0) + (random 150 - random 150),(_pos_patrol select 1) + (random 150 - random 150),0];

			_wp = _group addWaypoint [_newPos, 0];
			_wp setWaypointType "MOVE";
			_wp setWaypointCompletionRadius 20;
			_wp setWaypointCombatMode "RED";
		};
		_wp_1 = _group addWaypoint [_pos_patrol, 0];
		_wp_1 setWaypointType "MOVE";
		_wp_1 setWaypointCompletionRadius 20;
		_wp_1 setWaypointStatements ["true", format ["_spawn = [group this,%1] spawn BTC_add_waypoint_patrols;",_array]];
	}
	else
	{
		_wp setWaypointStatements ["true", format ["_spawn = [group this,%1] spawn BTC_add_waypoint_patrols;",_array]];
	};
	if (BTC_debug == 1) then 
	{
		_marker = createmarkerLocal [format ["Patrol_%1", _group getVariable "BTC_patrols_ID"] , [(_pos_patrol select 0) + random 15,(_pos_patrol select 1) + random 15,0]];
		format ["Patrol_%1", _group getVariable "BTC_patrols_ID"] setmarkertypelocal "mil_dot";
		format ["Patrol_%1", _group getVariable "BTC_patrols_ID"]  setMarkerTextLocal format ["P %1", _group getVariable "BTC_patrols_ID"];
		format ["Patrol_%1", _group getVariable "BTC_patrols_ID"]  setmarkerColorlocal "ColorRed";
		format ["Patrol_%1", _group getVariable "BTC_patrols_ID"]  setMarkerSizeLocal [0.5, 0.5];	
		diag_log text format ["ID: %1 (%3) POS: %2",_group getVariable "BTC_patrols_ID",_pos_patrol,typeof vehicle leader _group];
	};
};
BTC_m_fnc_only_server =
{
	_array = _this select 1;
	_type  = _array select 0;
	switch (true) do
	{
		case (_type == 0) : 
		{
			private ["_veh"];
			_veh = _array select 1;
			_veh spawn BTC_server_repair_wreck;
		};
		case (_type == 1) : 
		{
			[] spawn BTC_side_mission_select;
		};
		case (_type == 2) : 
		{
			BTC_sm_aborted = true;
		};
		case (_type == 3) : 
		{
			_save = [] spawn BTC_server_save;
		};
	};
};
BTC_s_console_execute =
{
	_array = _this select 1;
	_locality = _array select 0;
	if (_locality == "Server" || _locality == "All") then 
	{
		_param = _array select 1;
		_code = _array select 2;
		_param call compile _code;
	};
};
BTC_s_save_sitrep =
{
	_array = _this select 1;
	_title = _array select 0;
	_text = _array select 1;
	_author = _array select 2;
	_date = format ["%1.%2.%3  %4:%5", (date) select 0,(date) select 1,(date) select 2,(date) select 3,(date) select 4];
	_name = _title + " " + _author + " " + _date;
	_titles = (BTC_s_sitreps select 0) + [_name];
	_data   = (BTC_s_sitreps select 1) + [[_title,_author,_date,_text]];
	BTC_s_sitreps = [_titles,_data];
};
BTC_s_canc_sitrep =
{
	_array = _this select 1;
	_title = _array select 0;
	_titles = (BTC_s_sitreps select 0);
	_data   = (BTC_s_sitreps select 1);
	_id = _titles find _title;
	if (_id != -1) then 
	{
		_titles set [_id,0];_data set [_id,0];
		_titles = _titles - [0];_data = _data - [0];
		BTC_s_sitreps = [_titles,_data];
	};
};
BTC_s_send_sitrep =
{
	_name = _this select 1;
	_id = -1;
	{
		if (name _x == _name) then {_id = owner _x;};
	} foreach playableunits;
	if (_id > -1) then {_id publicVariableClient "BTC_s_sitreps";};
};
BTC_server_repair_wreck =
{
	_veh = _this;
	_type = typeOf _veh;
	_sleep_time = 3600;
	_array_pos = _veh getVariable "BTC_dont_delete";
	_save = [_type,_array_pos];
	_id = count BTC_veh_under_repair;
	BTC_veh_under_repair set [_id,_save];
	//BTC_veh_under_repair = BTC_veh_under_repair + [_save];
	switch (true) do
	{
		case (_type isKindOf "Car")   : {_sleep_time = 600;};
		case (_type isKindOf "Boat")  : {_sleep_time = 600;};
		case (_type isKindOf "Truck") : {_sleep_time = 900;};
		case (_type isKindOf "Tank")  : {_sleep_time = 1800;};
		case (_type isKindOf "Air")   : {_sleep_time = 1800;};
		default {_sleep_time = 900;};
	};
	deleteVehicle _veh;
	sleep _sleep_time;
	_veh  = createVehicle [_type, (_array_pos select 0), [], 0, "NONE"];
	_veh setDir (_array_pos select 1);_veh setPos (_array_pos select 0);
	_veh setVariable ["BTC_dont_delete",_array_pos,true];
	if(getNumber(configFile >> "CfgVehicles" >> typeof _veh >> "isUav")==1) then {
		createVehicleCrew _veh;    
	};
	BTC_veh_under_repair set [_id,0];
	BTC_veh_under_repair = BTC_veh_under_repair - [0];
};
BTC_AI_init =
{
	_group = _this select 0;
	if (isClass(configFile >> "cfgPatches" >> "asr_ai_main")) exitWith {};
	{
		_x setSkill ["aimingAccuracy", BTC_AI_skill];
		_x setSkill ["aimingShake", 0.6];
		_x setSkill ["aimingSpeed", 0.5];
		_x setSkill ["endurance", 0.6];
		_x setSkill ["spotTime", 0.5];
		_x setSkill ["courage", 0.4];
		_x setSkill ["spotDistance", 0.4];
		_x setSkill ["reloadSpeed", 1];
		if (leader _group == _x) then
		{
			_x setSkill ["commanding", 1];
		};
	} foreach units _group;
};
BTC_s_get_gear =
{
	private ["_array_mag","_id","_display_name","_count","_array_class","_array_bullet","_array_class_x","_array_bullet_x","_r_mag_d","_h_mag_d","_brack"];
	_player = _this select 0;
	_gear = [];
	_weapons = [];
	_prim_weap = primaryWeapon _player;
	_prim_items = primaryWeaponItems _player;
	_sec_weap = secondaryWeapon _player;
	_sec_items = secondaryWeaponItems _player;
	_items_assigned = assignedItems _player;
	_handgun = handgunWeapon _player;
	_handgun_items = handgunItems _player;
	if (_prim_weap != "") then {_weapons = _weapons + [_prim_weap]};
	if (_sec_weap != "") then {_weapons = _weapons + [_sec_weap]};
	if (_handgun != "") then {_weapons = _weapons + [_handgun]};
	_goggles = goggles _player;
	_headgear = headgear _player;
	_uniform = uniform _player;
	_uniform_items = uniformItems _player;
	_vest = vest _player;
	_vest_items = vestItems _player;
	_back_pack = backpack _player;
	_back_pack_items = backpackItems _player;
	_back_pack_weap = getWeaponCargo (unitBackpack _player);
	_weap_sel = currentWeapon _player;
	_weap_mode = currentWeaponMode _player;
	_fire_mode_array = getArray (configFile >> "cfgWeapons" >> _weap_sel >> "modes");
	_fire_mode = _fire_mode_array find _weap_mode;

	_magazinesAmmoFull = magazinesAmmoFull _player;
	_mag_uniform = [];_mag_vest = [];_mag_back = [];_mag_loaded_prim = [];_mag_loaded_sec = [];_mag_loaded_at = [];
	{
		if !(_x select 2) then
		{
			switch (true) do
			{
				case ((_x select 4) == "Vest" && ((_x select 3) != 0) && (getNumber(configFile >> "cfgMagazines" >> (_x select 0) >> "count") > 1))     : {_mag_vest = _mag_vest + [[(_x select 0),(_x select 1)]]};
				case ((_x select 4) == "Uniform" && ((_x select 3) != 0) && (getNumber(configFile >> "cfgMagazines" >> (_x select 0) >> "count") > 1))  : {_mag_uniform = _mag_uniform + [[(_x select 0),(_x select 1)]]};
				case ((_x select 4) == "Backpack" && ((_x select 3) != 0) && (getNumber(configFile >> "cfgMagazines" >> (_x select 0) >> "count") > 1)) : {_mag_back = _mag_back + [[(_x select 0),(_x select 1)]]};
			};
		}
		else
		{
			switch (true) do
			{
				case ((_x select 3) == 1)  : {_mag_loaded_prim = [(_x select 0),(_x select 1)]};
				case ((_x select 3) == 2)  : {_mag_loaded_sec = [(_x select 0),(_x select 1)]};
				case ((_x select 3) == 4) : {_mag_loaded_at = [(_x select 0),(_x select 1)]};
			};			
		};
	} foreach _magazinesAmmoFull;
	_ammo = [_mag_loaded_prim,_mag_loaded_sec,_mag_loaded_at,_mag_uniform,_mag_vest,_mag_back];
	_gear =
	[
		_uniform,
		_vest,
		_goggles,
		_headgear,
		_back_pack,
		_back_pack_items,
		_back_pack_weap,
		_weapons,
		_prim_items,
		_sec_items,
		_handgun_items,
		_items_assigned,
		_uniform_items,
		_vest_items,
		_weap_sel,
		_fire_mode,
		_ammo
	];
	//diag_log text format ["------------------------------------------",""];
	//{diag_log text format ["%1",_x]} foreach _gear;
	//diag_log text format ["------------------------------------------",""];
	_gear
};
BTC_save_positions_players =
{
	while {true} do
	{
		sleep 30;
		{
			_uid = getPlayerUid _x;
			_pos  = position _x;
			_gear = [_x] call BTC_s_get_gear;
			BTC_save_players_sys setVariable [_uid,[_pos,_gear]];
			if (BTC_players_uids find _uid == -1 && _uid != "") then {BTC_players_uids = BTC_players_uids + [_uid];};
		} foreach playableUnits;
	};
};
BTC_load_player_sys =
{
	_uid = _this select 0;
	//Let him initialize
	_time = time + 60;
	waitUntil {(({getPlayerUid _x == _uid} count playableUnits) > 0)|| time > _time};		
	{
		if (getPlayerUid _x == _uid) then
		{
			private ["_id"];
			_id = owner _x;
			if (!isNil {BTC_save_players_sys getVariable _uid}) then
			{
				_data = BTC_save_players_sys getVariable _uid;
				BTC_jip_client = _data;
				_id publicVariableClient "BTC_jip_client";
			};
			if (count BTC_city_under_attack > 0) then
			{
				{BTC_city_clear = [10,_x];_id publicVariableClient "BTC_city_clear";} foreach BTC_city_under_attack;
			};
		};
	} foreach playableUnits;
};
BTC_side_mission_select =
{
	BTC_sm_status = "";publicVariable "BTC_sm_status";BTC_sm_assigned = true;publicVariable "BTC_sm_assigned";
	_all = count BTC_side_missions;
	if (isNull BTC_sm_pos_selected) then {BTC_sm_pos_selected = BTC_sm_poss select (round (random ((count BTC_sm_poss) - 1)))} else 
	{
		private ["_obj","_cond"];
		_obj = BTC_sm_pos_selected;
		while {_obj == BTC_sm_pos_selected} do
		{
			BTC_sm_pos_selected = BTC_sm_poss select (round (random ((count BTC_sm_poss) - 1)));
			sleep 0.1;
		};
	};
	_n   = round (random (_all - 1));
	BTC_sm_PVEH = [BTC_sm_id,_n,BTC_sm_pos_selected];publicVariable "BTC_sm_PVEH";
	_sm = [BTC_sm_id,_n,BTC_sm_pos_selected] spawn BTC_side_mission_create;
	BTC_sm_id = BTC_sm_id + 1;BTC_sm_selected_n = _n;//publicVariable "BTC_sm_id";
};
BTC_side_mission_create =
{
	_id  = _this select 0;
	_n   = _this select 1;
	_pos = _this select 2;
	_sm = BTC_side_missions select _n;
	_title = _sm select 0;
	switch (true) do
	{
		case (_title == "Officer") : 
		{
			private ["_officer","_move_to","_house"];
			_houses = [_pos,100] call BTC_get_houses;
			_t_off = _sm select 3;
			if (count _houses == 0) then {_move_to = getpos _pos;} else 
			{
				_house  = _houses select (round (random ((count _houses) - 1)));
				_n_pos  = 0;
				while {format ["%1", _house buildingPos _n_pos] != "[0,0,0]" } do {_n_pos = _n_pos + 1};
				_move_to = _house buildingpos (round (random _n_pos));
			};
			_group = createGroup BTC_enemy_side;
			_group createUnit [_t_off, getpos _pos, [], 0, "NONE"];
			(leader _group) doMove _move_to;
			for "_i" from 0 to 5 do
			{
				_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
				_group createUnit [_unit_type, getpos _pos, [], 0, "NONE"];
				sleep 0.5;
			};
			if (BTC_p_skill == 1) then {[_group] call BTC_AI_init;};
			_wp = _group addWaypoint [_move_to, 0];_wp setWaypointType "HOLD";
			_off = leader _group;
			_off spawn
			{
				private ["_timeout"];
				_timeout = time + 60;
				waitUntil {sleep 1; (unitReady _this || moveToCompleted _this || moveToFailed _this || !alive _this || _timeout < time)};
				doStop _this;
			};
			//Condition
			[_off,_pos,_id] spawn 
			{
				_off = _this select 0;
				_pos = _this select 1;
				_id  = _this select 2;
				waitUntil {sleep 5; (!Alive _off || BTC_sm_aborted)};
				if (BTC_sm_aborted) then {BTC_sm_status = "N";publicVariable "BTC_sm_status";} else {BTC_sm_status = "Y";publicVariable "BTC_sm_status";};
				BTC_sm_aborted = false;BTC_sm_assigned = false;publicVariable "BTC_sm_assigned";
				_sm = [_pos,300] spawn BTC_city_deactivated;
			};
		};
		case (_title == "Prototype") : 
		{
			_t_prot = _sm select 3;
			_spawn_point = [(getpos _pos), 0, 150, 5, 0, 60 * (pi / 180), 0, []] call BIS_fnc_findSafePos;
			_prot = _t_prot createVehicle _spawn_point;
			_prot lock true;
			_group = createGroup BTC_enemy_side;
			for "_i" from 0 to 5 do
			{
				_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
				_group createUnit [_unit_type, _spawn_point, [], 0, "NONE"];
				sleep 0.5;
			};
			if (BTC_p_skill == 1) then {[_group] call BTC_AI_init;};
			_wp = _group addWaypoint [_spawn_point, 0];_wp setWaypointType "HOLD";_wp setWaypointCombatMode "RED";_wp setWaypointBehaviour "AWARE";
			[_prot,_pos,_id] spawn 
			{
				_prot = _this select 0;
				_pos = _this select 1;
				_id  = _this select 2;
				waitUntil {sleep 5; (!Alive _prot || BTC_sm_aborted)};
				if (BTC_sm_aborted) then {BTC_sm_status = "N";publicVariable "BTC_sm_status";} else {BTC_sm_status = "Y";publicVariable "BTC_sm_status";};
				BTC_sm_aborted = false;BTC_sm_assigned = false;publicVariable "BTC_sm_assigned";
				_sm = [_pos,300] spawn BTC_city_deactivated;deleteVehicle _prot;
			};		
		};
		case (_title == "Intel") : 
		{
			_t_intel = _sm select 3;
			_spawn_point = [(getpos _pos), 0, 150, 1, 0, 60 * (pi / 180), 0, []] call BIS_fnc_findSafePos;
			_suit = _t_intel createVehicle _spawn_point;
			_flag = "FlagSmall_F" createVehicle _spawn_point;
			_flag setVariable ["BTC_sm_interaction",1,true];
			BTC_m_PVEH = [3,_suit];publicVariable "BTC_m_PVEH";
			_group = createGroup BTC_enemy_side;
			for "_i" from 0 to 5 do
			{
				_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
				_group createUnit [_unit_type, _spawn_point, [], 0, "NONE"];
				sleep 0.5;
			};
			if (BTC_p_skill == 1) then {[_group] call BTC_AI_init;};
			_wp = _group addWaypoint [_spawn_point, 0];_wp setWaypointType "HOLD";_wp setWaypointCombatMode "RED";_wp setWaypointBehaviour "AWARE";
			[_suit,_pos,_id,_flag] spawn 
			{
				_suit = _this select 0;
				_pos  = _this select 1;
				_id   = _this select 2;
				_flag = _this select 3;
				waitUntil {sleep 5; (!Alive _suit || BTC_sm_aborted)};
				if (BTC_sm_aborted) then {BTC_sm_status = "N";publicVariable "BTC_sm_status";} else {BTC_sm_status = "Y";publicVariable "BTC_sm_status";};
				BTC_sm_aborted = false;BTC_sm_assigned = false;publicVariable "BTC_sm_assigned";
				_sm = [_pos,300] spawn BTC_city_deactivated;deleteVehicle _flag;
			};		
		};
		case (_title == "Radio Tower") : 
		{
			_t_radio = _sm select 3;
			_spawn_point = [(getpos _pos), 0, 150, 5, 0, 60 * (pi / 180), 0, []] call BIS_fnc_findSafePos;
			_radio = _t_radio createVehicle _spawn_point;
			_radio lock true;
			_group = createGroup BTC_enemy_side;
			for "_i" from 0 to 5 do
			{
				_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
				_group createUnit [_unit_type, _spawn_point, [], 0, "NONE"];
				sleep 0.5;
			};
			if (BTC_p_skill == 1) then {[_group] call BTC_AI_init;};
			_wp = _group addWaypoint [_spawn_point, 0];_wp setWaypointType "HOLD";_wp setWaypointCombatMode "RED";_wp setWaypointBehaviour "AWARE";
			[_radio,_pos,_id] spawn 
			{
				_radio = _this select 0;
				_pos = _this select 1;
				_id  = _this select 2;
				waitUntil {sleep 5; (!Alive _radio || BTC_sm_aborted)};
				if (BTC_sm_aborted) then {BTC_sm_status = "N";publicVariable "BTC_sm_status";} else {BTC_sm_status = "Y";publicVariable "BTC_sm_status";};
				BTC_sm_aborted = false;BTC_sm_assigned = false;publicVariable "BTC_sm_assigned";
				_sm = [_pos,300] spawn BTC_city_deactivated;deleteVehicle _radio;
			};		
		};
		case (_title == "Mortar Squad") : 
		{
			_group = createGroup BTC_enemy_side;
			_newZone = [(getpos _pos), 1, 200, 1, 0, 60 * (pi / 180), 0] call BIS_fnc_findSafePos;
			_mortar = createVehicle [BTC_type_mortar, _newZone, [], 0, "NONE"];
			_round_1 = createVehicle ["Land_BagFence_Round_F", [_newZone select 0,(_newZone select 1) + 1.5,0], [], 0, "NONE"];
			_round_2 = createVehicle ["Land_BagFence_Round_F", [_newZone select 0,(_newZone select 1) - 1.5,0], [], 0, "NONE"];
			_round_1 setDir 180;_round_1 setpos [_newZone select 0,(_newZone select 1) + 1.5,0];_round_2 setpos [_newZone select 0,(_newZone select 1) - 1.5,0];
			BTC_type_crewmen createUnit [_newZone, _group, "this moveinGunner _mortar"];
			_group createUnit [BTC_type_crewmen, _newZone, [], 0, "NONE"];
			_mortar_control = [_mortar] spawn BTC_mortar_control;
			[_mortar,_newZone] spawn 
			{
				_mortar  = _this select 0;
				_newZone  = _this select 1;
				waitUntil {sleep 5; ((count crew _mortar == 0) || BTC_sm_aborted)};
				if (BTC_sm_aborted) then {BTC_sm_status = "N";publicVariable "BTC_sm_status";} else {BTC_sm_status = "Y";publicVariable "BTC_sm_status";};
				BTC_sm_aborted = false;BTC_sm_assigned = false;publicVariable "BTC_sm_assigned";
				_sm = [_newZone,300] spawn BTC_city_deactivated;
			};		
		};
		case (_title == "Prisoners") : 
		{
			_t_pris = _sm select 3;
			_spawn_point = [(getpos _pos), 0, 150, 1, 0, 60 * (pi / 180), 0, []] call BIS_fnc_findSafePos;
			_group_civ = createGroup civilian;
			{
				_group_civ createUnit [_x, _spawn_point, [], 0, "NONE"];
				sleep 0.5;
			} foreach _t_pris;
			_wp_civ = _group_civ addWaypoint [_spawn_point, 0];_wp_civ setWaypointType "HOLD";
			{_x disableAI "MOVE";} foreach units _group_civ;
			_group = createGroup BTC_enemy_side;
			for "_i" from 0 to 5 do
			{
				_unit_type = BTC_type_units select (round (random ((count BTC_type_units) - 1)));
				_group createUnit [_unit_type, _spawn_point, [], 0, "NONE"];
				sleep 0.5;
			};
			BTC_m_PVEH = [6,_group_civ];publicVariable "BTC_m_PVEH";
			if (BTC_p_skill == 1) then {[_group] call BTC_AI_init;};
			_wp = _group addWaypoint [_spawn_point, 0];_wp setWaypointType "HOLD";_wp setWaypointCombatMode "RED";_wp setWaypointBehaviour "AWARE";
			_units = units _group_civ;
			{_x setVariable ["BTC_sm_interaction",1,true];} foreach _units;
			[_units,_pos] spawn 
			{
				_units = _this select 0;
				_pos = _this select 1;
				waitUntil {sleep 5; (({Alive _x} count _units == 0) || ({_x distance (getMarkerPos "respawn_west") < 100} count _units == ({Alive _x} count _units) && ({Alive _x} count _units > 0)) || BTC_sm_aborted)};
				if (({Alive _x} count _units == 0) || BTC_sm_aborted) then {BTC_sm_status = "N";publicVariable "BTC_sm_status";} else {BTC_sm_status = "Y";publicVariable "BTC_sm_status";};
				BTC_sm_aborted = false;BTC_sm_assigned = false;publicVariable "BTC_sm_assigned";
				_sm = [_pos,300] spawn BTC_city_deactivated;
				if ({Alive _x} count _units != 0) then
				{
					_cond = false;
					while {!_cond} do
					{
						_array_p = [];
						{
							if (Alive _x && _x distance (getMarkerPos "respawn_west") < 300) then {_array_p = _array_p + [_x]};
						} foreach playableunits;
						if (count _array_p == 0) then {_cond = true;};
					};
					{deletevehicle _x;} foreach _units;
				};
			};		
		};
	};
	if (BTC_HC_name == "") then {[_pos] spawn BTC_sm_spawn_units;} else {BTC_to_HC = [2,_pos];BTC_HC_id publicVariableClient "BTC_to_HC";};
};
BTC_sm_spawn_units =
{
	_pos = _this select 0;
	_players = playersNumber BTC_player_side;_n = 0;
	switch (true) do
	{
		case (_players < 5) : {_n = 3 + random 2;};
		case (_players > 5 && _players < 11) : {_n = 6 + random 2;};
		case (_players > 11) : {_n = 10 + random 2;};
	};
	for "_i" from 0 to _n do
	{
		[BTC_enemy_side,[_pos],90,1] call BTC_spawn_inf_group;
	};
	_veh_n = 0;
	switch (true) do
	{
		case (BTC_enemy_n == 1) : {_veh_n = round (random 1);};
		case (BTC_enemy_n == 2) : {_veh_n = round (random 2);};
		case (BTC_enemy_n == 3) : {_veh_n = round (random 4);};
	};	
	for "_i" from 1 to _veh_n do
	{
		if (typeName _pos != "ARRAY") then {_pos = getPos _pos;};
		_loc_2 = [(_pos select 0) + ((random 50) - (random 50)), (_pos select 1) + ((random 50) - (random 50)), 0];
		[BTC_enemy_side,[_loc_2],"",80,2] call BTC_spawn_veh_group;
	};
};
BTC_service_quads =
{
	_vehs = _this;
	{_x setVariable ["BTC_start_pos",[typeOf _x,0,getpos _x,getDir _x]];} foreach _this;
	_var = [];
	sleep 3;
	while {true} do
	{
		{
			private ["_var"];
			_var = [];
			_var = _x getVariable "BTC_start_pos";
			if ((_x distance (_var select 2)) > 15 && (count crew _x) == 0) then {_x setVariable ["BTC_start_pos",[(_var select 0),(_var select 1) + 5,(_var select 2),(_var select 3)]];} else {_x setVariable ["BTC_start_pos",[(_var select 0),0,(_var select 2),(_var select 3)]];};
			if (((_x getVariable "BTC_start_pos") select 1) > 60) then {_x setdamage 0;_x setfuel 1;_x setDir (_var select 3);_x setPos (_var select 2);};
			_x setdamage 0;
		} foreach _this;
		{_x setVehicleAmmo 1;} foreach BTC_defenses;
		sleep 5;
	};
};
BTC_server_save =
{
	if (isClass(configFile >> "cfgPatches" >> "iniDB")) then {"BTC_war_storm" call iniDB_delete;"BTC_war_storm" call iniDB_CRC32;};
	_players = [];
	_data = [];
	_cities = [];
	_fobs = [];
	_vehicles = [];
	_ammobox = [];
	{
		_uid = getPlayerUid _x;
		_pos  = position _x;
		_gear = [_x] call BTC_s_get_gear;
		BTC_save_players_sys setVariable [_uid,[_pos,_gear]];
		if (BTC_players_uids find _uid == -1 && _uid != "") then {BTC_players_uids = BTC_players_uids + [_uid];};
	} foreach playableUnits;
	{
		private ["_data"];
		_data = BTC_save_players_sys getVariable _x;
		if (isClass(configFile >> "cfgPatches" >> "iniDB")) then
		{
			["BTC_war_storm", "mission", _x, _data] call iniDB_write;
		}
		else {_players = _players + [[_x,_data]];};
	} foreach BTC_players_uids;
	_data = _data + [date];
	{
		if (_x getVariable "BTC_city_status" == 1) then {_cities = _cities + [getpos _x];};
	} foreach BTC_main_city;
	{
		private ["_pos"];
		_pos = getpos _x;
		_fobs = _fobs + [_pos];
	} foreach BTC_fob_placed;
	{
		if (!isNil {_x getVariable "BTC_dont_delete"}) then 
		{
			private ["_type","_array_pos","_save","_dir","_pos"];
			_type = typeOf _x;
			_pos  = getposATL _x;
			_dir  = getDir _x;
			_dam  = getDammage _x;
			_array_pos = _x getVariable "BTC_dont_delete";
			_save = [_type,_pos,_dir,_dam,_array_pos];
			_vehicles = _vehicles + [_save];
		};
	} foreach vehicles;
	_array_ammo = allMissionObjects "ReammoBox_F";
	{
		if (Alive _x && _x distance (getMarkerPos "respawn_west") > 200 && _x distance [- 5000,- 5000,0] > 2000 && !(_x isKindOf "groundweaponholder")) then
		{
			private ["_type","_pos","_dir"];
			_type = typeOf _x;
			_pos  = getposATL _x;
			_dir  = getDir _x;
			_ammobox = _ammobox + [[_type,_pos,_dir]];
		};
	} foreach _array_ammo;
	if (isClass(configFile >> "cfgPatches" >> "iniDB")) then
	{
		["BTC_war_storm", "mission", "players_uids", BTC_players_uids] call iniDB_write;
		["BTC_war_storm", "mission", "data", _data] call iniDB_write;
		["BTC_war_storm", "mission", "cities", _cities] call iniDB_write;
		["BTC_war_storm", "mission", "fobs", _fobs] call iniDB_write;
		["BTC_war_storm", "mission", "vehicles", _vehicles] call iniDB_write;
		["BTC_war_storm", "mission", "vehicles_rep", BTC_veh_under_repair] call iniDB_write;
		["BTC_war_storm", "mission", "ammo", _ammobox] call iniDB_write;
		["BTC_war_storm", "mission", "sitreps_0", (BTC_s_sitreps select 0)] call iniDB_write;
		["BTC_war_storm", "mission", "sitreps_1", (BTC_s_sitreps select 1)] call iniDB_write;
	} else {profileNameSpace setVariable ["BTC_war_storm",[_players,_data,_cities,_fobs,_vehicles,BTC_veh_under_repair,_ammobox,BTC_s_sitreps]];saveProfileNamespace;};
	BTC_m_PVEH = [5,"Session saved!"];publicVariable "BTC_m_PVEH";
	/*
	_text = format ["%1",profileNameSpace getVariable "BTC_war_storm"];BTC_m_PVEH = [5,_text];publicVariable "BTC_m_PVEH";
	_text = format ["%1 - %2",typename (call compile (["BTC_war_storm", "mission", "vehicles"] call iniDB_read)),call compile (["BTC_war_storm", "mission", "vehicles"] call iniDB_read)];BTC_m_PVEH = [5,_text];publicVariable "BTC_m_PVEH";
	_text = format ["%1",(profileNameSpace getVariable "BTC_war_storm") select 0];diag_log text format ["%1",_text];
	{if (_x isKindOf "MRAP_01_base_F") then {_marker = createmarkerLocal [format ["%1_marker", getpos _x], getPos _x];format ["%1_marker", getpos _x] setMarkerTextLocal "Hunter";format ["%1_marker", getpos _x] setMarkerSizeLocal [0.5,0.5];};} foreach (vehicles);
	{if (side _x == independent) then {_x setDamage 1;}} foreach allUnits;
	hint format ["%1",(nearestObject [player, "Land_Tyre_F"])];[(nearestObject [player, "Land_Tyre_F"])] spawn BTC_city_cleared;
	for "_i" from 0 to (count BTC_main_city) do 
	{
		if (_i != 0) then
		{
			[BTC_main_city select _i] spawn BTC_city_cleared;
		};
	};
	*/
};
BTC_server_load =
{
	_players = _this select 0;
	_data = _this select 1;
	_cities = _this select 2;
	_fobs = _this select 3;
	_vehicles = _this select 4;
	_rep_vehs = _this select 5;
	_ammo = _this select 6;
	BTC_s_sitreps = _this select 7;
	{
		private ["_name","_stuff"];
		_name = _x select 0;
		_stuff = _x select 1;
		BTC_save_players_sys setVariable [_name,_stuff];
	} foreach _players;
	setDate (_data select 0);
	{_id = owner _x;BTC_m_PVEH = [11,(_data select 0)];_id publicVariableClient "BTC_m_PVEH";} foreach playableunits;
	{
		private ["_city"];
		_city = nearestObject [_x, "Land_Tyre_F"];
		_city setVariable ["BTC_city_status",1,true];
		BTC_main_city_array = BTC_main_city_array - [_city];
	} foreach _cities;
	{
		_struc = createVehicle [BTC_fob_sign, _x, [], 0, "NONE"];
		_flag  = createVehicle ["FlagPole_F", _x, [], 0, "NONE"];
		_flag setpos [_x select 0,_x select 1,0];_struc setpos [_x select 0,_x select 1,0];
		_flag setVariable ["BTC_mobile_west",format ["FOB_%1",BTC_fob_id],true];
		BTC_fob_placed = BTC_fob_placed + [_flag];publicVariable "BTC_fob_placed";
		BTC_vehs_mobile_west_str = BTC_vehs_mobile_west_str + [format ["FOB_%1",BTC_fob_id]];
		BTC_fob_id = BTC_fob_id + 1;publicVariable "BTC_fob_id";publicVariable "BTC_vehs_mobile_west_str";
	} foreach _fobs;
	{
		if (!isNil {_x getVariable "BTC_dont_delete"}) then {{deletevehicle _x;} foreach crew _x;deletevehicle _x;};
	} foreach vehicles;
	{
		_type = _x select 0;
		_pos = _x select 1;
		_dir = _x select 2;
		_dam = _x select 3;
		_data = _x select 4;
		_veh  = createVehicle [_type, _pos, [], 0, "NONE"];
		_veh setDir _dir;_veh setPos _pos;_veh setdamage _dam;
		_veh setVariable ["BTC_dont_delete",_data,true];
		if(getNumber(configFile >> "CfgVehicles" >> typeof _veh >> "isUav") == 1) then 
		{
			createVehicleCrew _veh;    
		};		
	} foreach _vehicles;
	if (count _rep_vehs > 0) then
	{
		{
			_type = _x select 0;
			_data = _x select 1;
			_veh  = createVehicle [_type, (_data select 0), [], 0, "NONE"];
			_veh setDir (_data select 1);_veh setPos (_data select 0);
			_veh setVariable ["BTC_dont_delete",_data,true];
			if(getNumber(configFile >> "CfgVehicles" >> typeof _veh >> "isUav") == 1) then 
			{
				createVehicleCrew _veh;    
			};
		} foreach _rep_vehs;
	};
	{
		_type = _x select 0;
		_pos = _x select 1;
		_dir = _x select 2;
		_box  = createVehicle [_type, _pos, [], 0, "NONE"];
		_box setDir _dir;_box setPos _pos;
	} foreach _ammo;
	//veh
	true
};
